//
//  MYRouter.m
//  HZTC_Stock
//
//  Created by MayerF on 2017/5/24.
//  Copyright © 2017年 MayerF. All rights reserved.
//

#import "MYRouter.h"
#import <objc/runtime.h>

@interface MYRouter ()
@property (strong, nonatomic) NSMutableDictionary *routes;
@end

@implementation MYRouter
- (NSMutableDictionary *)routes
{
    if (!_routes) {
        _routes = [[NSMutableDictionary alloc] init];
    }
    
    return _routes;
}

#pragma mark -
#pragma mark public
+ (instancetype)shared
{
    static MYRouter *router = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        if (!router) {
            router = [[self alloc] init];
        }
    });
    return router;
}

- (void)map:(NSString *)route toControllerClass:(Class)controllerClass
{
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                                              route,@"route",
                                                    controllerClass,@"controllerClass", nil];
    
    self.routes[route] = dict;
}

- (UIViewController *)matchController:(NSString *)route
{
    return [self matchController:route params:nil];
}

- (UIViewController *)matchController:(NSString *)route params:(NSDictionary *)params
{
    if (![self.routes.allKeys containsObject:route]) {
        return nil;
    }
    
    Class controllerClass = self.routes[route][@"controllerClass"];
    UIViewController *viewController = [[controllerClass alloc] init];
    
    if (params) {
        if ([viewController respondsToSelector:@selector(setParams:)]) {
            [viewController performSelector:@selector(setParams:)
                                 withObject:[params copy]];
        }
    }
    return viewController;
}

- (void)map:(NSString *)route toBlock:(MYRouterBlock)block
{
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          route,@"route",
                          [block copy],@"block", nil];
    
    self.routes[route] = dict;
}

- (MYRouterBlock)matchBlock:(NSString *)route
{
    if (![self.routes.allKeys containsObject:route]) {
        return nil;
    }
    MYRouterBlock block = self.routes[route][@"block"];
//    [self.routes removeObjectForKey:route];
    return block;
}
- (void)matchDeleteBlock:(NSString *)route
{
    if ([self.routes.allKeys containsObject:route]) {
        [self.routes removeObjectForKey:route];
    }
}

@end

#pragma mark - UIViewController Category

@implementation UIViewController (MYRouter)

static char kAssociatedParamsObjectKey;

- (void)setParams:(NSDictionary *)paramsDictionary
{
    objc_setAssociatedObject(self, &kAssociatedParamsObjectKey, paramsDictionary, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSDictionary *)params
{
    return objc_getAssociatedObject(self, &kAssociatedParamsObjectKey);
}

@end
